package com.abocode.aichat.server.delivery;

import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.delivery.inbound.InboundServerDeliver;
import com.abocode.aichat.server.delivery.outbound.OutboundServerDeliver;
import com.abocode.aichat.server.entity.Entity;
import com.abocode.aichat.server.entity.EntityImpl;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.stanza.Stanza;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.entity.Entity;
import com.abocode.aichat.server.entity.EntityImpl;
import com.abocode.aichat.server.reply.Replies;
import com.abocode.aichat.server.stanza.Stanza;

import java.util.Map;

/**
 * Created by franky-21.
 */
public class ControlServerDeliver implements ServerDeliver<Replies> {

    private ServerRuntimeContext serverRuntimeContext;

    private InboundServerDeliver inboundServerDeliver;

    private OutboundServerDeliver outboundServerDeliver;

    public InboundServerDeliver getInboundServerDeliver() {
        return inboundServerDeliver;
    }

    public void setInboundServerDeliver(InboundServerDeliver inboundServerDeliver) {
        this.inboundServerDeliver = inboundServerDeliver;
    }

    public OutboundServerDeliver getOutboundServerDeliver() {
        return outboundServerDeliver;
    }

    public void setOutboundServerDeliver(OutboundServerDeliver outboundServerDeliver) {
        this.outboundServerDeliver = outboundServerDeliver;
    }

    @Override
    public ServerRuntimeContext getServerRuntimeContext() {
        return serverRuntimeContext;
    }

    @Override
    public void setServerRuntimeContext(ServerRuntimeContext serverRuntimeContext) {
        this.serverRuntimeContext = serverRuntimeContext;
        inboundServerDeliver.setServerRuntimeContext(serverRuntimeContext);
        outboundServerDeliver.setServerRuntimeContext(serverRuntimeContext);
    }

    @Override
    public void deliver(Replies replies, Stanza stanza) {
        if (replies != null) {
            inboundServerDeliver.deliver(replies, stanza);
//            if (isOut(stanza)) {
//                outboundServerDeliver.deliver(replies, stanza);
//            } else {
//                inboundServerDeliver.deliver(replies, stanza);
//            }
        }
    }

    private boolean isOut(Stanza stanza) {
        if ("chat".equals(stanza.namespace())) {
            Map map = stanza.body();
            Entity entity = EntityImpl.parse(String.valueOf(map.get("to")));
            return !serverRuntimeContext.getDomain().equals(entity.getDomain());
        }
        if ("presence".equals(stanza.namespace())) {
            Map map = stanza.body();
            Entity entity = EntityImpl.parse(String.valueOf(map.get("to")));
            return !serverRuntimeContext.getDomain().equals(entity.getDomain());
        }
        return false;
    }
}
